package org.panda.spring;

import org.panda.spring.advice.MyAdvice;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MockAopBeanPostProcesor implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //目的，对UserServiceImpl中的show1和show2方法进行增强，增强方法存在于MyAdvice中
        //问题1：刷选service.impl包下的所有的类的所有方法都可以进行增强
        //问题2：MyAdvice怎么获取到？ 解决方案：从Spring容器中获得MyAdvice
        if(bean.getClass().getPackage().getName().equals("org.panda.spring.service.impl")){
            Object proxyBean = Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            MyAdvice myAdvice = applicationContext.getBean(MyAdvice.class);
                            myAdvice.beforeAdvice();
                            Object result = method.invoke(bean,args);
                            myAdvice.afterAdvice();
                            return result;
                        }
                    }
            );
            return proxyBean;
        }

        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
